<template>
	<view class="content">


		<u-navbar class="navbar" :fixed="false" :title="title" titleWidth="700" :autoBack="true"
			:safeAreaInsetTop="true" leftIconColor="#fff">
			<view class="u-nav-slot" slot="left">
				<view class="NavbarLeft">
					<!-- 回退按钮 -->
					<u-icon name="arrow-left" :duration="0" size="20" color="#fff" @click="GoBack"></u-icon>
				</view>
			</view>
			<view slot="right">
				<u-icon name="scan" size="28" color="#fff" @click="openScanCode"></u-icon>
			</view>

		</u-navbar>
		<view class="contentBox">
			<view class="container">
				<uni-forms ref="baseForm" :modelValue="formData">
					<view class="form-item-row">
						<uni-forms-item label="单据日期:" label-width="auto">
							<input v-model="formData.FDate" type="text" placeholder="请选择单据日期" disabled
								@click="Timeshow=true">
							</input>
						</uni-forms-item>
					</view>
				</uni-forms>
			</view>
			<view class="table" style="overflow:auto;">
				<table style="white-space:nowrap;">
					<tr>
						<th>序号</th>
						<th>出库仓库</th>
						<th>出库库位</th>
						<th>产品名称</th>
						<th>批次号</th>
						<th>出库数量</th>
						<th>计量单位</th>
						<th>操作</th>
					</tr>
					<tr v-for="(item, index) in tableData">
						<td>{{index + 1}}</td>
						<td>{{item.FWarehouseName}}</td>
						<td>{{item.FStorageCode}}</td>
						<td>{{item.ProductName}}</td>
						<td>{{item.FBatchNo}}</td>
						<td>
							<input v-model="item.FQty" type="number" placeholder="请输入" />
						</td>
						<td>{{item.UnitName}}</td>
						<td>
							<view>
								<u-button type="warning" size="small" text="删除"
									@click="del_tableData(index,item)"></u-button>
							</view>
						</td>
					</tr>
				</table>

			</view>
			<view class="BottomBox">
				<button class="CommonBtnSize content_bottom_primary_Btn" @click="submit('add')"
					v-if="!formData.FStockID && ApproveBack('提交')">提交</button>
				<button class="CommonBtnSize content_bottom_primary_Btn" @click="submit('edit')"
					v-if="formData.FStockID && !formData.Approve && ApproveBack('修改')">修改</button>
				<button class="CommonBtnSize content_bottom_primary_Btn" @click="submit('edit',1)"
					v-if="formData.FStockID && !formData.Approve && ApproveBack('审核')">审核</button>
				<button class="CommonBtnSize content_bottom_primary_Btn" @click="approve()"
					v-if="formData.FStockID && formData.Approve && ApproveBack('取消审核')">取消审核</button>
			</view>

		</view>

		<view class="search" @click="openScanCode" style="z-index: 1;width: 80rpx;height: 80rpx;">
			<u-icon name="scan" size="80rpx" color="#fff"></u-icon>
		</view>




		<u-datetime-picker :show="Timeshow" v-model="value1" mode="datetime" @cancel='Timeshow=false'
			:closeOnClickOverlay="true" @close="Timeshow=false" @confirm='pickerConfirm'
			:formatter="formatter"></u-datetime-picker>



	</view>

</template>

<script>
	import {
		getFormatDateTime,
	} from '../common/base.js';

	export default {
		data() {
			return {
				title: '原料出库',

				formData: {
					FStockID: 0,
					Approve: null,
					FCode: '',
					FDate: ''

				},
				tableData: [],
				routeIndex: 0,
				Timeshow: false,
				value1: Number(new Date()),
				TableIndex: 0,

				BtnApprove: [], // 按钮权限数组
			};
		},
		mounted() {
			var that = this
			uni.$on('RawMaterialsCK_Choice', function(ret) {
				if (ret.type == '产品') {
					that.tableData[that.TableIndex] = Object.assign(that.tableData[that.TableIndex], ret.data);
				}
			})
		},
		onLoad(item) {
			var that = this
			/**获取按钮权限 start**/
			//console.log(this.$store.state.appConfigInfo.ModuleInfo_All)

			let foundNode = null;
			// 获取页面按钮权限
			for (const module of this.$store.state.appConfigInfo.ModuleInfo_All) {
				if (module.TreeTypeName === '生产模块') {
					for (const node of module.Node) {
						if (node.APFunName === '原料出库') {
							foundNode = JSON.parse(JSON.stringify(node));
							break; // 找到后立即退出内层循环  
						}
					}
					if (foundNode) {
						break;
					}
				}
			}
			if (foundNode) {
				this.BtnApprove = foundNode['IconApprove'];
			}

			console.log(this.BtnApprove)
			/**获取按钮权限 end**/

			if (item.FStockID) {
				that.GetRawMaterialsCK(item.FStockID)
			} else {
				this.formData.FDate = that.$utils.dateFormat(new Date(), 'Y-MM-dd hh:mm:ss')

			}

		},
		onUnload() {
			uni.$off('RawMaterialsCK_Choice')
		},
		onShow() { // 每次页面显示时

			plus.screen.lockOrientation('landscape-primary');

		},
		onBackPress(options) { // 监听页面返回
			plus.screen.lockOrientation('portrait-primary');

		},
		methods: {
			ApproveBack(str) {
				// let that = this;
				// let Type = that.BtnApprove.some(item => {
				// 	return item.MenuName == str
				// })

				// return Type;
				return true;
			},
			calc_FQty(item) {
				item.FQty = Number(item.barrelNumber) * Number(item.barrelWeight);
			},
			openScanCode() {
				let that = this;
				that.$scanPopup.openScan({
					success: (res) => {

						console.log(res.result)


						function getIsCPPCM(res) {
							let IsCPPCM = false;

							function startsWithPCMRegex(str) {
								return /^CPPCM/.test(str);
							}
							try {
								IsCPPCM = startsWithPCMRegex(res.result) && res.result.split('|')[0] == 'CPPCM'
							} catch (e) {
								IsCPPCM = false;
							}

							return IsCPPCM
						}


						let IsCPPCM = getIsCPPCM(res)

						console.log(IsCPPCM)

						if (IsCPPCM) {
							let obj = {
								code: res.result.split('|')[1],
								batch: res.result.split('|')[2],
							}
							console.log(obj)
							that.Request.request('GKJ_YLCK_Scan_CPPCM', obj, function(res) {
								if (res.status == 200) {
									if (res.data.ds.length) {
										if (res.data.ds[0].status && res.data.ds[0].status == 500) {
											that.$utils.msg(res.data.ds[0].msg)
										} else {
											that.tableData.push(res.data.ds[0]);
										}

									} else {
										that.$utils.msg('当前扫描的产品批次码不存在');

									}
								} else {
									that.$utils.msg('请求失败，请重试');

								}
							}, function(err) {
								console.log(JSON.stringify(err))
							})
						} else {
							that.$utils.msg('请扫描产品批次码')
						}
					}
				})
			},
			del_tableData(index, item) {
				var that = this;
				let content = '是否删除此条数据？'
				uni.showModal({
					title: '提示',
					content: content,
					success: function(res) {
						if (res.confirm) {
							that.tableData.splice(index, 1);
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				})
			},
			GoBack() {
				uni.navigateBack()
			},
			GetRawMaterialsCK(id) {
				var that = this
				try {
					that.Request.request('GKJ_YLCK_Detail', {
						FStockID: id
					}, (ret) => {
						console.log(ret.data);

						that.formData = ret.data.ds[0]

						that.tableData = ret.data.ds1
						if (that.formData.FCode) {
							that.title = `原料出库 ${that.formData.FCode}`;
						}
						that.$forceUpdate()
					})
				} catch (e) {
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},
			submit_Request(type, isApprove) {
				var that = this;

				let obj = {
					type: type,
					FStockID: that.formData.FStockID,
					FDate: that.formData.FDate,
					ProductIDs: that.tableData.map((item) => {
						return item.ProductID
					}).join(','),
					FCKWarehouseIDs: that.tableData.map((item) => {
						return item.FCKWarehouseID
					}).join(','),
					FStorageIDs: that.tableData.map((item) => {
						return item.FStorageID
					}).join(','),
					FBatchNos: that.tableData.map((item) => {
						return item.FBatchNo
					}).join(','),
					FQtys: that.tableData.map((item) => {
						return item.FQty
					}).join(','),
					UnitIDs: that.tableData.map((item) => {
						return item.UnitID
					}).join(','),
				}
				console.log(obj)
				that.Request.request('GKJ_YLCK_Submit', obj, function(ret) {
					console.log(ret);
					if (ret.status == 200) {
						if (ret.data.ds[0].hasOwnProperty('status') &&
							ret.data.ds[0].status == 500) {

							that.$utils.msg(ret.data.ds[0].msg);
						} else {
							uni.$emit('refresh_RawMaterialsCK'); // 刷新列表
							that.$utils.msg(ret.data.ds[0].msg);
							that.GetRawMaterialsCK(ret.data.ds[0].FStockID)

							if (isApprove) {
								that.approve();
							}
						}
					} else {

						that.$utils.msg('请求失败请重试')
					}
				})
			},
			submit(type, isApprove) {
				var that = this;
				if (type == 'add' || (type == 'edit' && !isApprove)) {
					uni.showModal({
						title: '提示',
						content: '是否提交？',
						success: function(res) {
							if (res.confirm) {
								that.submit_Request(type, isApprove);
							} else if (res.cancel) {
								// console.log('用户点击取消');
							}
						}
					})
				} else {
					that.submit_Request(type, isApprove);
				}

			},
			approve() {
				var that = this;
				let obj = {
					KeyID: that.formData.FStockID,
					type: that.formData.Approve ? -1 : 1,
				}
				console.log(obj)
				that.Request.request('GKJ_YLCK_Approve', obj, function(ret) {
					console.log(ret);
					if (ret.status == 200) {
						if (ret.data.ds[0].hasOwnProperty('status') &&
							ret.data.ds[0].status == 500) {
							that.$utils.layer.alert(ret.data.ds[0].msg)
							//that.$utils.msg(ret.data.ds[0].msg);
						} else {
							uni.$emit('refresh_RawMaterialsCK'); // 刷新列表
							that.$utils.msg(ret.data.ds[0].msg);
							that.GetRawMaterialsCK(ret.data.ds[0].FStockID)
						}
					} else {

						that.$utils.msg('请求失败请重试')
					}
				})
			},
			formatter(type, value) { // 时间选择器数据格式化
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},
			dateFormat(val) { // 格式化时间
				var that = this;
				if (!that.$utils.isEmpty(val)) {
					return that.$utils.dateFormat(new Date(val), 'Y-MM-dd hh:mm:ss');
				} else {
					return that.$utils.dateFormat(new Date(), 'Y-MM-dd hh:mm:ss');
				}
			},
			// 获取时间
			pickerConfirm(e) {
				var time = this.dateFormat(e.value)
				this.formData.FDate = time
				this.Timeshow = false
				this.$forceUpdate()
			},
		}
	}
</script>

<style lang="scss">
	@import "../css/index.css";

	.s {
		border-bottom: 2px solid #51d0d0;
	}

	.BottomBox {
		position: absolute;
		left: 0;
		bottom: 0;
		height: 50px;
	}

	.contentBox {
		overflow: auto;
		height: calc(100vh - 100px);
	}

	.table table tr:hover input {
		background-color: transparent;
	}
</style>